package com.example.administrator.newfragmentation.fragment.wx.first;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.administrator.newfragmentation.R;
import com.example.administrator.newfragmentation.adpter.wx.ChatAdapter;
import com.example.administrator.newfragmentation.entity.Chat;
import com.example.administrator.newfragmentation.event.StartBrotherEvent;
import com.example.administrator.newfragmentation.event.TabSelectedEvent;
import com.example.administrator.newfragmentation.fragment.wx.WxMainFragment;
import com.example.administrator.newfragmentation.fragmentMain.BaseFragment;
import com.example.administrator.newfragmentation.listener.wx.OnItemClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class WechatFirstTabFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.recy)
    RecyclerView recy;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;

    private ChatAdapter adapter;
    private boolean mInAtTop = true;
    private int mScrollTotal;

    public static WechatFirstTabFragment newInstance() {
        WechatFirstTabFragment fragment = new WechatFirstTabFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_wechat_first_tab, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorAccent));
        recy.setLayoutManager(new LinearLayoutManager(_mActivity));
        recy.setHasFixedSize(true);
        final int space = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0.5f, getResources().getDisplayMetrics());
        recy.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(0, 0, 0, space);
            }
        });

        adapter = new ChatAdapter(_mActivity);
        recy.setAdapter(adapter);

        recy.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mScrollTotal += dy;
                if (mScrollTotal <= 0) {
                    mInAtTop = true;
                } else {
                    mInAtTop = false;
                }
            }
        });

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position, View view, RecyclerView.ViewHolder vh) {
                // 因为启动的MsgFragment是MainFragment的兄弟Fragment,所以需要MainFragment.start()

                // 这里我使用EventBus通知父MainFragment处理跳转(接耦),
                EventBus.getDefault().post(new StartBrotherEvent(MsgFragment.newInstance(adapter.getMsg(position))));

                // 也可以像使用getParentFragment()的方式,拿到父Fragment的引用来操作 (不建议)
//              ((MainFragment) getParentFragment()).startMsgBrother(MsgFragment.newInstance());
            }
        });

        List<Chat> chatList = initDatas();
        adapter.setDatas(chatList);
    }

    private List<Chat> initDatas() {
        List<Chat> msgList = new ArrayList<>();

        String[] name = new String[]{"小黄", "小李", "小张", "老王", "小马"};
        String[] chats = new String[]{"小黄的消息", "小李的消息", "小张的消息", "老王的消息", "小马的消息"};

        for (int i = 0; i < 15; i++) {
            int index = (int) (Math.random() * 5);
            Chat chat = new Chat();
            chat.name = name[index];
            chat.message = chats[index];
            msgList.add(chat);
        }
        return msgList;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        recy.setAdapter(null);
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    /**
     * Reselected Tab
     * 再次点击
     */
    @Subscribe
    public void onTabSelectedEvent(TabSelectedEvent event) {
        if (event.position != WxMainFragment.FIRST) return;

        if (mInAtTop) {
            refreshLayout.setRefreshing(true);
            onRefresh();
        } else {
            scrollToTop();
        }
    }

    private void scrollToTop() {
        recy.smoothScrollToPosition(0);
    }

    @Override
    public void onRefresh() {
        refreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(false);
            }
        }, 1000);
    }
}
